package com.cykj.pos.insideLogin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cykj.common.config.RuoYiConfig;
import com.cykj.common.constant.Constants;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.core.domain.model.LoginUser;
import com.cykj.common.core.redis.RedisCache;
import com.cykj.framework.web.service.TokenService;
import com.cykj.pos.enums.bizstatus.CommEnum;
import com.cykj.pos.insideLogin.domain.InsideUser;
import com.cykj.pos.insideLogin.domain.ao.InsideUserAO;
import com.cykj.pos.insideLogin.mapper.InsideLoginMapper;
import com.cykj.pos.insideLogin.service.InsideLoginService;
import com.cykj.pos.service.IDataSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @author wangjiaqi
 * @date 2021/12/29
 */
@Service
public class InsideLoginServiceImpl extends ServiceImpl<InsideLoginMapper, InsideUser> implements InsideLoginService {

    @Resource
    private InsideLoginMapper insideLoginMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IDataSecurityService ticketService;

    @Autowired
    private RuoYiConfig config;

    @Override
    public List<InsideUser> findUser(String nickName) {
        return insideLoginMapper.findUser(nickName);
    }

    @Override
    public AjaxResult loginOwn(InsideUserAO insideUserAO) {
        //获取权限
        Set<String> permissions = insideLoginMapper.getPermissions(insideUserAO.getUserName(), insideUserAO.getNickName());
        //获取User信息
        SysUser userInfo = insideLoginMapper.getUserInfo(insideUserAO.getUserName(), insideUserAO.getNickName());

        LoginUser login = new LoginUser();
        login.setPermissions(permissions);
        login.setUser(userInfo);

        String token = tokenService.createToken(login);

        AjaxResult ajax = AjaxResult.success();
        String redisKey = insideUserAO.getUserName() + "-login-error-counts";
        Integer errorCounts = redisCache.getCacheObject(redisKey);
        if (errorCounts != null) {
            redisCache.deleteObject(redisKey);
        }
        LoginUser loginUser = tokenService.getLoginUser(token);
        ajax.put(Constants.TOKEN, token);
        ajax.put("loginUser", loginUser);
        // 获得腾讯秘钥信息
        ajax.put(CommEnum.SECRETID.getKey(), CommEnum.SECRETID.getValue());
        ajax.put(CommEnum.SECRETKEY.getKey(), CommEnum.SECRETKEY.getValue());
        ajax.put(CommEnum.BUCKETNAME.getKey(), CommEnum.BUCKETNAME.getValue());
        ajax.put(Constants.TICKET, ticketService.createTicket(insideUserAO.getUserName(), config.getTicketTimeOut()));
        return ajax;
    }
}
